import pprint
import shutil

from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.playbook import Play
from git import Repo
import os

import sys
from collections import namedtuple
# 核心类
# 用于读取YAML和JSON格式的文件
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.parsing.dataloader import DataLoader
# 用于存储各类变量信息
from ansible.vars.manager import VariableManager
# 用于导入资产文件
from ansible.inventory.manager import InventoryManager
# 操作单个主机信息
from ansible.inventory.host import Host
# 操作单个主机组信息
from ansible.inventory.group import Group
# 状态回调，各种成功失败的状态
from ansible.plugins.callback import CallbackBase
from collections import namedtuple

from ansible.cli.playbook import PlaybookCLI


class AnsibleClient:

    @staticmethod
    def invite(self, ):
        pass


if __name__ == '__main__':


    dl = DataLoader()
    im = InventoryManager(
        loader=dl,
        sources=[
            "/Users/zhaojinhui/Desktop/Auto/autonsole/.gitRepoHub/autoble/example/k8s/inventories"
        ]
    )

    vm = VariableManager(loader=dl, inventory=im)



    # im.add_group("etcd")
    #
    # im.add_host("etcd1", "etcd")
    # im.add_host("etcd2", "etcd")
    # im.add_host("etcd3", "etcd")

    # im.add_dynamic_host({
    #     "host_name": "etcd1",
    #     "groups": ["etcd"]
    # }, {"refresh": True})
    #
    # im.add_dynamic_host({
    #     "host_name": "etcd2",
    #     "groups": ["etcd"]
    # }, {"refresh": True})
    #
    # im.add_dynamic_host({
    #     "host_name": "etcd3",
    #     "groups": ["etcd"]
    # }, {"refresh": True})

    allGroups = im.get_groups_dict()
    print("allGroups", allGroups)

    # hostEtcd1 = im.get_host('etcd1')
    # hostEtcd1.set_variable("ansible_host", "1.1.1.1")
    #
    # hostEtcd2 = im.get_host('etcd2')
    # hostEtcd2.set_variable("ansible_host", "2.2.2.2")
    #
    # hostEtcd3 = im.get_host('etcd3')
    # hostEtcd3.set_variable("ansible_host", "3.3.3.3")





    play_source = dict(name="Ansible Play",  # 任务名称
                       hosts="localhost",  # 目标主机，可以填写具体主机也可以是主机组名称
                       gather_facts="no",  # 是否收集配置信息

                       # tasks是具体执行的任务，列表形式，每个具体任务都是一个字典
                       tasks=[
                           dict(action=dict(module="shell", args="hostname", warn=False))
                       ])
    play = Play().load(play_source, variable_manager=vm, loader=dl)

    print(im.hosts.keys())
    for host in im.hosts.values():
        print(host.vars)
        pprint.pprint(vm.get_vars(host=host))

    #以下两种方式，因为没有传入或传入localhost，localhost不属于任何自定义的组，所以拿不到组变量
    #但是能拿到组和组的成员，再从成员拿到组变量
    #因为ansible层层优先级的变量设计方式，不管在哪一个优先级设置了变量，最终执行task时的变量就是
    print('\n\n\npprint.pprint(vm.get_vars(play, stage="all"))')
    pprint.pprint(vm.get_vars(play, stage="all"))
    print('\n\n\npprint.pprint(vm.get_vars(play, stage="play"))')
    pprint.pprint(vm.get_vars(play, stage="play"))
    print('\n\n\npprint.pprint(vm.get_vars(play, stage="task"))')
    pprint.pprint(vm.get_vars(play, stage="task")) #默认值
    pprint.pprint(vm.get_vars(play, host=im.hosts.get('localhost')))

    print(im.groups.keys())
    for group in im.groups.values():
        print(group.vars)


    tqm = TaskQueueManager(
        inventory=im,
        variable_manager=vm,
        loader=dl,
        passwords={}
    )

    tqm.run(play)

    # playbook_path = "/path/to/playbook"
    #
    # playbook = PlaybookExecutor(
    #     playbooks=[playbook_path],
    #     inventory=im,
    #     variable_manager=vm,
    #     loader=dl,
    #     passwords={"conn_pass": None}
    # )
    #
    # # 运行 playbook
    # results = playbook.run()

    #
    # 目录结构是
    # inventories
    # inventories/hosts.ini
    # inventories/group_vars/all.yaml
    # inventories/group_vars/etcd.yaml
    #
    # 代码如下
    # dl = DataLoader()
    # im = InventoryManager(
    #     loader=dl,
    #     sources=[
    #         "/Users/zhaojinhui/Desktop/Auto/autonsole/.gitRepoHub/autoble/example/k8s/inventories"
    #     ]
    # )
    #
    # vm = VariableManager(loader=dl, inventory=im)
    #
    # vm 获取不到 inventories/group_vars/all.yaml、inventories/group_vars/etcd.yaml中的变量
    #
    # 如何才能获取到




